cmake_minimum_required(VERSION 3.15)

####################### toolchains for crosscompile #######################

# set(CMAKE_TOOLCHAIN_FILE toolchain-arm-none-eabi-gcc.cmake)
set(CMAKE_SYSTEM_NAME               Generic)
set(CMAKE_SYSTEM_PROCESSOR          arm)

set(CMAKE_AR                        arm-none-eabi-ar)
set(CMAKE_ASM_COMPILER              arm-none-eabi-gcc)
set(CMAKE_C_COMPILER                arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER              arm-none-eabi-g++)
set(CMAKE_LINKER                    arm-none-eabi-ld)
set(CMAKE_OBJCOPY                   arm-none-eabi-objcopy)

set(CMAKE_C_FLAGS                   "-Wno-psabi --specs=nosys.specs -fdata-sections -ffunction-sections -Wl,--gc-sections")
set(CMAKE_CXX_FLAGS                 "${CMAKE_C_FLAGS} -fno-exceptions")

set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

set(CMAKE_EXECUTABLE_SUFFIX_C   .elf)
set(CMAKE_EXECUTABLE_SUFFIX_CXX .elf)
set(CMAKE_EXECUTABLE_SUFFIX_ASM .elf)

############# project settiongs ########################################

project(blink LANGUAGES C ASM)

add_definitions(-DSTM32F1) 

############### library #######################################################

set(LIBOPENCM3_DIR ${CMAKE_SOURCE_DIR}/libopencm3)
add_custom_target(libopencm3 make TARGETS=stm32/f1 WORKING_DIRECTORY ${LIBOPENCM3_DIR})
link_directories(${LIBOPENCM3_DIR}/lib)

include_directories(
        ${LIBOPENCM3_DIR}/include
        )

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -mcpu=cortex-m3 -mthumb -mthumb-interwork -msoft-float -std=c99 -Os -ffunction-sections -fdata-sections ")
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -Wall --std=c++14")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -T ${CMAKE_SOURCE_DIR}/libopencm3.ld -nostartfiles -lc -lnosys --specs=rdimon.specs -Wl,--gc-sections")

########### project and library dependency #######################################################
add_executable(${PROJECT_NAME} main.c)

#build before main target
add_dependencies(${PROJECT_NAME} libopencm3)

target_link_libraries(${PROJECT_NAME} opencm3_stm32f1)
